/*
 * File Name: CheckBitmapActivity.java 
 * History:
 * Created by zhangzhiyong on 2013-9-22
 */
package com.denny.devdemo.clearer.worker;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.widget.ImageView;
import android.widget.Toast;

import com.denny.devdemo.util.LogUtils;

public class CheckBitmapActivity extends Activity {
    // ==========================================================================
    // Constants
    // ==========================================================================
    private final static String PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
            + "/sina/weibo/.weibo_pic_new/0bf84d8c1a39a99cf62a4b1202babd67";
    private final static String PATH1 = Environment.getExternalStorageDirectory().getAbsolutePath() + "/UCenter.apk";
    // ==========================================================================
    // Fields
    // ==========================================================================
    private ImageView mImageView;

    // ==========================================================================
    // Constructors
    // ==========================================================================
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtils.e("CheckBitmap:" + PATH1);
        Bitmap bitmap = BitmapFactory.decodeFile(PATH1);
        if (bitmap == null) {
            Toast.makeText(this, "不是图片", Toast.LENGTH_LONG).show();
        } else {
            mImageView = new ImageView(this);
            mImageView.setImageBitmap(bitmap);
            setContentView(mImageView);

        }
        
        Intent intent1 = new Intent(this,ScanService.class);
        startService(intent1);
        
        // getProperties();
//        new Thread() {
//            public void run() {
//                LogUtils.markStart("####start");
//                scanRoot();
//                LogUtils.elapsed("####end");
//            };
//        }.start();
//        try {
//            List<String> list = new ArrayList<String>();
//            File f = AESUtil.decryptFile(getAssets().open("close.txt"), "txt", "123456",this);
//            BufferedReader reader = new BufferedReader(new FileReader(f));
//            String s = null;
//            while ((s = reader.readLine()) != null) {
//                list.add(s);
//                LogUtils.e("readline:" + s);
//            }
//            f.delete();//读取完成后删除解密码文件
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        
    }

    // ==========================================================================
    // Getters
    // ==========================================================================

    // ==========================================================================
    // Setters
    // ==========================================================================

    // ==========================================================================
    // Methods
    // ==========================================================================

    public void scanRoot() {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            return;
        }
        File rootFile = Environment.getExternalStorageDirectory();
        LogUtils.e("rootPath:------" + rootFile.getAbsolutePath());
        File[] fs = rootFile.listFiles();
        List<File> files = Arrays.asList(fs);
        Collections.sort(files, new Comparator<File>() {

            @Override
            public int compare(File f1, File f2) {
                // TODO Auto-generated method stub
                return f1.getName().compareToIgnoreCase(f2.getName());
            }
        });
        if (files != null && files.size() > 0) {
            for (int i = 0; i < files.size(); i++) {
                File f = files.get(i);
                if (f.isDirectory()) {
                    LogUtils.e("root list Directory:------" + f.getName());
                    File[] tempFiles = f.listFiles();
                    if (skipDirectory()) {// 跳过部分文件
                        LogUtils.e("skipDirectory:------" + f.getAbsolutePath() + "," + f.length());
                    } else if (tempFiles == null || tempFiles.length == 0) {
                        LogUtils.e("no files-----:" + f.getAbsolutePath() + "," + f.length());
                    } else if (checkAppDirectory()) {

                    } else if (checkAdDirectory()) {

                    } else {
                         scanFiles(f.getAbsolutePath());
                    }

                } else if (f.isFile()) {
                    // LogUtils.e("file:-----"+f.getAbsolutePath()+","+f.length());
                    if (getExtFileName(f).equals("apk")) {
                        if (isApkValid(f.getAbsolutePath())) {
                            LogUtils.e("-------------file is apk");
                        } else {
                            LogUtils.e("---------------file is apk bad");
                        }
                    } else if (checkPic(f)) {
                        LogUtils.e("---------------file is pic:" + f.getAbsolutePath());
                    }

                }
            }
        }

    }

    private boolean checkPic(File f) {
        if (getExtFileName(f).equalsIgnoreCase("jpg") || getExtFileName(f).equalsIgnoreCase("gif")
                || getExtFileName(f).equalsIgnoreCase("png")) {
            return true;
        } else {
            Bitmap bitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
            if (bitmap != null) {
                return true;
            }
        }
        return false;
    }

    public boolean isApkValid(String path) {
        PackageManager pm = this.getPackageManager();
        try {
            if (pm.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES) == null) {
                return false;
            }
        } catch (Exception e) {
            LogUtils.e(e);
        }
        return true;
    }

    private String getExtFileName(File f) {
        if (f != null) {
            int index = f.getName().lastIndexOf(".");
            if (index != -1) {
                // LogUtils.e("getExtFileName:" + f.getName().substring(index + 1));
                return f.getName().substring(index + 1);
            }
        }
        return "";
    }

    private boolean checkAdDirectory() {
        return false;
    }

    private boolean checkAppDirectory() {
        return false;
    }

    private void scanFiles(String absolutePath) {
        String [] deep = absolutePath.split("/");
        if(deep.length > 5){
            LogUtils.e("over deep:"+absolutePath);
            return;
        }
        File subFile = new File(absolutePath);
        File[] files = subFile.listFiles();
        if (files != null && files.length > 0) {
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                if (f.isDirectory()) {
                    File[] tempFiles = f.listFiles();
                    if (tempFiles == null || tempFiles.length == 0) {
                        LogUtils.e("no files-----:" + f.getAbsolutePath() + "," + f.length());
                    } else {
                        scanFiles(f.getAbsolutePath());
                    }

                } else if (f.isFile()) {
                    if (getExtFileName(f).equals("apk")) {
                        if (isApkValid(f.getAbsolutePath())) {
                            LogUtils.e("-------------subfile is apk");
                        } else {
                            LogUtils.e("---------------subfile is apk bad");
                        }
                    } else if (checkPic(f)) {
                        LogUtils.e("---------------subfile is pic:" + f.getAbsolutePath());
                    }

                }
            }
        }
    }

    private boolean skipDirectory() {
        return false;
    }

    public void getProperties() {
        LogUtils.e("getProperties");
        Properties p = new Properties();
        try {
            Map<String, String> map = new HashMap<String, String>();
            BufferedReader in = new BufferedReader(new FileReader(new File(Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/prop.properties")));
            String data = "";
            LogUtils.e("=====" + in.readLine());
            while ((data = in.readLine()) != null) {
                String[] s = data.split("=");
                p.setProperty(s[0], s[1]);
                LogUtils.e("-----" + s[0] + "," + s[1]);
            }
            File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/prop1.properties");
            if (!f.exists()) {
                f.createNewFile();
            }
            p.store(new FileOutputStream(f), "#####");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // ==========================================================================
    // Inner/Nested Classes
    // ==========================================================================
}
